import React, { Component } from 'react';
import {
    StyleSheet,
    View,
    Image,
    TouchableHighlight,
    Animated,
    Easing,
    ScrollView,
    KeyboardAvoidingView,
    Platform,
    Dimensions,
    NativeModules
} from 'react-native';
import Label from '../label/index';
import PropTypes from 'prop-types';
import Color from '../../config/theme/standard/color';
import Fonts from '../../config/theme/standard/fonts';
// import Constant from '../../config/theme/standard/constant';

// const width = Constant.screenWidth;
// const height = Constant.screenHeight;
const aHeight = 370;
const maxHeight = 500;
const  { StatusBarManager } = NativeModules;
export default class Layer extends Component {

    constructor(props) {
        super(props);
        this.state = {
            offset: new Animated.Value(0),
            hide: this.props.hide,
            prevPropsHide: this.props.hide,
            statusBarHeight : 0
        };
        this.contentHeight = 0;
    }
    
    componentDidMount(){
        if (Platform.OS === 'ios') { // 获取状态栏高度
            StatusBarManager.getHeight(statusBarHeight => {
                this.setState({
                    statusBarHeight: statusBarHeight.height
                }) 
             })
        }
         // 监听屏幕宽度变化
         this.dimensionsListener= Dimensions.addEventListener('change', ()=>{
            this.forceUpdate();
        });
    }
    componentWillUnmount(){
        // 移除监听
        this.dimensionsListener && this.dimensionsListener.remove();
        
    }

    //显示动画
    _in() {
        Animated.parallel([
            Animated.timing(
                this.state.offset,
                {
                    easing: Easing.linear,
                    duration: 500,
                    toValue: 1,
                }
            )
        ]).start();
    }
    //隐藏动画
    _out() {
        Animated.parallel([
            Animated.timing(
                this.state.offset,
                {
                    easing: Easing.linear,
                    duration: 500,
                    toValue: 0,
                }
            )
        ]).start((finished) => this.setState({ hide: true }));
    }
    _return() {
        if (this.props.showMask && this.props.clickMask) {
            this.props.destroy();
            this.setState({ hide: true });
        }
        if (this.props.showMask && this.props.maskClickEvent) {
            this.props.maskClickEvent()
        }

    }



    _close() {
        this.props.destroy();
        this.setState({ hide: true });
        if (this.props.iconFunc) {
            this.props.iconFunc();
        }
    }

    _iconFunc() {
        if (this.props.iconFunc) {
            this.props.iconFunc();
        } else {
            this._return();
        }
    }

    _operateFunc() {
        if (this.props.operateFunc) {
            this.props.operateFunc();
        }
    }


    static getDerivedStateFromProps(nextProps, prevState) {
        if (('hide' in nextProps) && (nextProps.hide !== prevState.prevPropsHide)) {
            return {
                prevPropsHide: nextProps.hide,
                hide: nextProps.hide
            };
        }
        return null;
    }

    render() {
        let { showMask, clickMask, title, titleStyle, innerHeight, icon, iconStyles,
            operateText, operateTextStyles, content, wrapperType }
            = this.props;
        let { offset, hide,statusBarHeight } = this.state;
        let rightContentStyle = [styles.rightContent];
        const width = Dimensions.get('window').width;
        const height = Dimensions.get('window').height;

        let trueHeight;

        //判断机型
        if(Platform.OS === 'ios' && width < height){
            if(height/width >1.8 && statusBarHeight > 20){
                trueHeight = height -34
            }else{
                trueHeight = height
            }
        }
        let containerStyle = [styles.container, Platform.OS == 'harmony' &&{ zIndex:1 }];
        if (!showMask) {
            containerStyle.push({ backgroundColor: 'transparent' })
        }

        let isClickMask = showMask && clickMask ? true : false;
        //遮罩层
        // let mask;
        // if (isClickMask) {
        //     mask = (
        //         <TouchableHighlight style={maskStyle} activeOpacity={Color.shadow.opacity} underlayColor={Color.shadow.background} onPress={() => this._return()}>
        //             <View><Label /></View>
        //         </TouchableHighlight>
        //     );
        // } else {
        //     mask = (
        //         <TouchableHighlight style={maskStyle} underlayColor='transparent'>
        //             <View><Label /></View>
        //         </TouchableHighlight>
        //     );
        // }
        //左侧图标
        let leftIcon;
        if (icon) {
            leftIcon = (
                <TouchableHighlight style={styles.floatReturn} underlayColor='transparent' onPress={() => this._iconFunc()}>
                    <Image style={[styles.icon, iconStyles]} source={icon} />
                </TouchableHighlight>
            );
        } else {
            leftIcon = (
                <TouchableHighlight style={styles.floatReturn} underlayColor='transparent' onPress={() => this._close()}>
                    <Image style={[styles.icon, iconStyles]} source={require('../../assets/icon_layer_return.png')} />
                </TouchableHighlight>
            );
        }
       
        if (innerHeight > maxHeight) {
            innerHeight = aHeight;
        }

        if (hide) {
            return (<View />)
        } else {
            if (wrapperType == 'view') {
                return (
                    <View style={containerStyle}>
                        <TouchableHighlight
                            //underlayColor={showMask ? 'rgba(0,0,0,.4)' : 'transparent'}
                            underlayColor={'transparent'}
                            onPress={() => this._return()}>
                            <View style={{ height: height, width: width, backgroundColor: 'transparent' }}></View>
                        </TouchableHighlight>
                        <View style={[styles.float, { width: width, height: innerHeight }]}>
                            <View style={[styles.floatHead, { width: width }]}>
                                <View style={[operateText!='' ?{ width: 96 }: {width:44}]}>
                                    {leftIcon}
                                </View>
                                <View style={[operateText!='' ?{ width: width - 96 - 96 }:{ width: width - 44 - 44},{alignItems: 'center'}]}>
                                    <Label text={title} labelStyle={[styles.title, titleStyle]} numberOfLines={1}/>
                                </View>
                                <TouchableHighlight underlayColor='transparent' onPress={() => this._operateFunc()}>
                                    <View style={[operateText!='' ? rightContentStyle :{width:44}]}>
                                        <Label text={operateText} labelStyle={[styles.operateText, operateTextStyles]} />
                                    </View>
                                </TouchableHighlight>
                            </View>
                            {content}
                        </View>
                    </View>
                );
            } else if (wrapperType == 'scrollView') {
                return (
                    <ScrollView
                        style={containerStyle}
                        keyboardShouldPersistTaps={'never'}
                        contentContainerStyle={styles.contentContainerStyle}
                    >
                        <KeyboardAvoidingView
                            behavior={'position'}
                            keyboardVerticalOffset={Platform.OS == 'ios' ? '0' : (-this.contentHeight)}
                            contentContainerStyle={styles.contentContainerStyle}
                        >
                            <TouchableHighlight
                                //underlayColor={showMask ? 'rgba(0,0,0,.4)' : 'transparent'}
                                underlayColor={'transparent'}
                                onPress={() => this._return()}>
                                <View style={{ height: Platform.OS === 'ios' ? trueHeight : height, width: width, backgroundColor: 'transparent' }}></View>
                            </TouchableHighlight>
                            <View style={[styles.float, { width: width, height: innerHeight }, Platform.OS == 'harmony' &&{ zIndex:1 }]}>
                                <View style={[styles.floatHead, { width: width }]}>
                                    <View style={[operateText!='' ?{ width: 96 }: {width:44}]}>
                                        {leftIcon}
                                    </View>
                                    <View style={[operateText!='' ?{ width: width - 96 - 96 }:{ width: width - 44 - 44},{alignItems: 'center'}]}>
                                        <Label text={title} labelStyle={[styles.title, titleStyle]} numberOfLines={1}/>
                                    </View>
                                    <TouchableHighlight underlayColor='transparent' onPress={() => this._operateFunc()}>
                                        <View style={[operateText!='' ? rightContentStyle :{width:44}]}>
                                            <Label text={operateText} labelStyle={[styles.operateText, operateTextStyles]} />
                                        </View>
                                    </TouchableHighlight>
                                </View>
                                <View onLayout={(e) => {
                                    let { height } = e.nativeEvent.layout
                                    this.contentHeight = height;
                                }}>
                                    {content}
                                </View>
                            </View>
                        </KeyboardAvoidingView>
                    </ScrollView>
                );
            }
        }
    }
    //显示浮层方法
    show() {
        if (this.state.hide) {
            this.setState({ hide: false }, this._in());
        }
    }
    //隐藏浮层方法
    hide() {
        this._return();
    }
}

Layer.propTypes = {
    //是否显示遮罩
    showMask: PropTypes.bool,
    //点击遮罩收起浮层
    clickMask: PropTypes.bool,
    //浮层标题
    title: PropTypes.string,
    //浮层标题样式
    titleStyle: PropTypes.object,
    //浮层高度
    innerHeight: PropTypes.number,
    //左侧icon
    icon: PropTypes.any,
    //左侧icon样式
    iconStyles: PropTypes.object,
    //左侧icon操作
    iconFunc: PropTypes.func,
    //右侧文本
    operateText: PropTypes.string,
    //右侧文本样式
    operateTextStyles: PropTypes.object,
    //右侧文本操作
    operateFunc: PropTypes.func,
    //内部内容
    content: PropTypes.any,
    hide: PropTypes.bool,
    destroy: PropTypes.func,
    wrapperType: PropTypes.string
}

Layer.defaultProps = {
    showMask: true,
    clickMask: false,
    title: "标题",
    innerHeight: aHeight,
    operateText: "操作",
    destroy: () => { },
    hide: true,
    wrapperType: 'view'
}

const styles = StyleSheet.create({
    container: {
        position: "absolute",
        backgroundColor: 'rgba(0, 0, 0, 0.4)',
        top: 0,
        bottom: 0,
        left: 0,
        right: 0
    },
    contentContainerStyle: {
        alignItems: 'center',
        justifyContent: 'center',
    },
    maskClickArea: {
        position: "absolute",
        backgroundColor: 'transparent',
        top: 0,
        bottom: 0,
        left: 0,
        right: 0,
        zIndex:1,
        alignItems: 'center',
        justifyContent: 'center',
    },
    // mask: {
    //     justifyContent: "center",
    //     backgroundColor: Color.shadow.background,
    //     opacity: Color.shadow.opacity,
    //     position: "absolute",
    //     // width: width,
    //     height: height
    // },
    float: {
        // width: width,
        height: aHeight,
        backgroundColor: Color.white,
        position: "absolute",
        bottom: 0,
        right: 0,
        left: 0,
        alignItems: "center",
    },
    floatHead: {
        // width: width,
        height: 50,
        flexDirection: 'row',
        justifyContent: 'space-between',
        //paddingTop: 12,
        //paddingBottom: 13,
        //paddingRight: 12,
        //paddingLeft: 8,
        //borderTopWidth: 1,
        borderBottomWidth: 1,
        borderColor: Color.border
    },
    title: {
        fontSize: Fonts.layer.titleFontSize,
        color: Color.layer.title,
        fontWeight: '400',
        paddingTop: 12,
        paddingBottom: 13
    },
    icon: {
        width: 44,
        height: 44,
        marginTop: 3,
        marginBottom: 3,
        resizeMode: 'contain'
    },
    rightContent: {
        width: 96,
        marginTop: 14,
        marginBottom: 14,
        paddingRight:15,
        alignItems: 'flex-end',
        justifyContent: 'center'
    },
    operateText: {
        fontSize: Fonts.layer.operateFontSize,
        color: Color.layer.operateText,
        fontWeight: '400',

    },
    floatReturn: {
        marginLeft: 0
    },

});
